﻿#include <string>
#include <iostream>
#include <chrono>
#include "singleton.hpp"
#include "asyncrequest.hpp"
#include "json.hpp"
using json = nlohmann::json;
using namespace std::literals;

void test1(int a,int b,std::string c) {
	std::cout << a << "," << b << "," << c << std::endl;
}

class Tool {
public:
	void test2(int a, int b, std::string c) {
		std::cout << a << "," << b << "," << c << std::endl;
	}
};

int main() {
	//1. 创建request center,模板参数为 结果的类型
	auto& center = hhfox::Singleton<hhfox::RequestCenter<json>>::createInstance(10);

	//2. 创建 request,异步运行
	Tool tool;
	auto request = center->createRequest("req1", &Tool::test2, tool, 1, 2, "121212121");
	auto a = request->getResult();
	std::string dd = "aaaaa";
	auto request2 = center->createRequest("req2",test1, 5, 7, std::move(dd));
	auto b = request2->getResult();

	std::thread t([&center,&request,&request2]() {
		//4. 另外的线程拿到结果后，根据 reqID ,回馈到调用线程
		center->emitResult("req1", json({ {"code",0},{"reson","ok"} }));

		center->emitResult("req2", json({ {"code",404},{"reson","error"} }));
	});

	//5. 调用线程等待结果
	if (a.wait_for(2s) == std::future_status::timeout) {
		std::cout << "a timeout\n";
	}
	else {
		std::cout << a.get() << std::endl;
	}

	//5. 调用线程等待结果
	if (b.wait_for(2s) == std::future_status::timeout) {
		std::cout << "b timeout\n";
	}
	else {
		std::cout << b.get() << std::endl;
	}

	t.join();
	return 0;
}
